import { omit } from "lodash-es"

import type { PlasmoMessaging } from "@plasmohq/messaging"

/**
 * 获取公司信息
 * @param uid 店铺 id
 * @returns
 */
const getCompanyInfo = async (uid: string): Promise<CompanyInfo> => {
  const url = `https://scportal.taobao.com/quali/quali_show.htm?uid=${uid}&qualitype=1`
  const html = await fetch(url).then((res) => res.text())
  const licenseKeys: Record<keyof CompanyInfo, string> = {
    company_name: "公司名称",
    unified_social_id: "统一社会信用代码",
    address: "注册地址",
    legal_representative: "法定代表人",
    nature_of_business: "经营范围",
    business_term: "经营期限"
  }
  const clearfixRegex = /<div\s+class="clearfix">([\s\S]*?)<\/div>\s*<\/div>/gs
  const subElementRegex = /<div\s+class="label">([\s\S]*?)<\/div>\s+<div\s+class="fn-left width500">([\s\S]*?)<\/div>/g
  const clearfixMatches = html.match(clearfixRegex)
  if (!clearfixMatches) return Object.keys(licenseKeys).reduce((pre, key) => ((pre[key] = ""), pre), {} as CompanyInfo)
  const info = clearfixMatches.reduce((prev, curr) => {
    const subElementMatches = [...curr.matchAll(subElementRegex)]
    for (const [, label, value] of subElementMatches) {
      prev.push({ label: label.replace("：", "").trim(), value: value.trim() })
    }
    return prev
  }, [])
  const license = Object.keys(licenseKeys).reduce((pre, key) => {
    const label = licenseKeys[key]
    const target = info.find((item) => item.label.includes(label))
    target ? (pre[key] = target.value) : (pre[key] = "")
    return pre
  }, {} as CompanyInfo)
  return license
}

/**
 * 获取店铺信息
 */
const getShopInfo = async (url: string) => {
  const html = await fetch(url).then((res) => res.text())
  const clearfixRegex = /<span\s+class="tm-shop-age-num">([\d\D]*?)<\/span>/gs
  const clearfixMatches = html.match(clearfixRegex)
  if (clearfixMatches) {
    const results = clearfixMatches.map((match) => match.replace(/<[^>]+>/g, ""))
    return { opening_time: results[0] }
  }

  const regex = /"shopDurationNum":"([^"]+)"/
  const match = regex.exec(html)
  if (match && match[1]) {
    return { opening_time: match[1] }
  }

  return { opening_time: "/" }
}

/**
 * 获取企业信息
 */
const handler: PlasmoMessaging.MessageHandler = async (req, res) => {
  const { uid, shopUrl } = req.body
  const companyInfo = await getCompanyInfo(uid)
  // const companyInfo = {}
  const shopInfo = await getShopInfo(shopUrl)
  res.send({
    ...omit(req.body, ["goodsInShop", "labels", "shopRankImgUrl"]),
    ...companyInfo,
    ...shopInfo
  })
}

export default handler
